import storeTool from './storeTool'
import apiTool from './apiTool'
import * as vant from "vant";
const { showFailToast } = vant;
export default function (url, params, config = {}) {
  const auth = storeTool.auth.get()
  const type = Object.prototype.toString.call(params.body)
  const { isRedirect = true, isShowWarring = true, isResolve = false } = config
  return new Promise((resolve, reject) => {
    const headers = {
      'content-Type': 'application/json',
      Authorization: `${auth.tokenType || ''} ${auth.token || ''}`,
      'X-Application-name': 'app',
      ...(config.headers || {})
    }
    if (type == '[object FormData]') {
      delete headers['Content-Type']
    }
    fetch(url, {
      ...params,
      headers: {
        ...headers,
        ...params.headers
      }
    })
      .then(e => {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise(async resolve => {
          if (e.status == 403) {
            resolve({ status: e.status })
          } else {
            resolve({
              ...(await e.json()),
              status: e.status
            })
          }
        })
      })
      .then(e => {
        // 如果401直接重定向
        if (e.code == 401) {
          if (isRedirect) {
            apiTool.jumpLogin()
          } else {
            reject(e)
          }
        } else if ( // 如果code等于200或者满足表单结构的话 允许继续
          e.code == 200 ||
          e.result == 'true' ||
          type == '[object FormData]' ||
          e.access_token
        ) {
          if (type == '[object FormData]' || e.access_token || isResolve) {
            resolve(e)
          } else {
            // e.data.__proto__.result = e
            resolve(e.data || e.result)
          }
        } else if (e.status == 500) { // 接口出现崩溃异常
          // apiTool.showFail()
          reject(e)
        } else {
          isShowWarring && e.msg && showFailToast(e.msg) // 接口出现错误异常
          reject(e)
        }
      })
      .catch(e => {
        reject(e)
      })
  })
}
